package com.acheli.registry.network.packet;

import com.acheli.ACHeli;
import com.acheli.registry.config.CustomDataBus;
import com.acheli.registry.event.CustomDynamicEntityPool;
import com.acheli.registry.network.ACHMessages;
import com.acheli.rideable.entites.ComponentEntity;
import com.acheli.rideable.entites.RideableEntity;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;

import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;

import static com.acheli.registry.entity.ACHEntities.RIDEABLE_COMPONENT_ENTITY_TYPE;

public class VehiclePackRloadEventC2SPacket {
    // 添加字符串字段
    private final CompoundTag tag;

    // 从字节缓冲区解码
    public VehiclePackRloadEventC2SPacket(FriendlyByteBuf buf) {
        this.tag = buf.readNbt();
    }

    public VehiclePackRloadEventC2SPacket() {
        tag = new CompoundTag();
    }

    // 编码到字节缓冲区
    public void toBytes(FriendlyByteBuf buf) {
        buf.writeNbt(tag);
    }

    private boolean handle(Supplier<NetworkEvent.Context> supplier) {
        ACHeli.LOGGER.info("VehiclePackRloadEventC2SPacket");
        NetworkEvent.Context context = supplier.get();
        context.enqueueWork(() -> {
            CustomDataBus.load();
            List<Entity> list = CustomDynamicEntityPool.entityMap.get(RideableEntity.class);
            for (Entity entity : list) {
                if (entity instanceof RideableEntity rideableEntity) {
                    rideableEntity.reloadData();
                }
            }
        });
        return true;
    }

    public static void register(SimpleChannel channel) {
        channel.messageBuilder(VehiclePackRloadEventC2SPacket.class, ACHMessages.id(), NetworkDirection.PLAY_TO_SERVER)
                .decoder(VehiclePackRloadEventC2SPacket::new)
                .encoder(VehiclePackRloadEventC2SPacket::toBytes)
                .consumerMainThread(VehiclePackRloadEventC2SPacket::handle)
                .add();
    }
}